package com.jd.pet.service.impl;

import com.jd.basic.exception.BusinessException;
import com.jd.basic.service.impl.BaseServiceImpl;
import com.jd.basic.util.*;
import com.jd.order.domain.OrderPetAcquisition;
import com.jd.order.mapper.OrderPetAcquisitionMapper;
import com.jd.org.domain.Employee;
import com.jd.org.domain.Shop;
import com.jd.org.mapper.EmployeeMapper;
import com.jd.org.mapper.ShopMapper;
import com.jd.pet.domain.SearchMasterMsg;
import com.jd.pet.domain.SearchMasterMsgAuditLog;
import com.jd.pet.dto.OrderDto;
import com.jd.pet.mapper.SearchMasterMsgAuditLogMapper;
import com.jd.pet.mapper.SearchMasterMsgMapper;
import com.jd.pet.query.SearchMasterMsgQuery;
import com.jd.pet.service.ISearchMasterMsgService;
import com.jd.user.domain.Logininfo;
import com.jd.user.domain.User;
import com.jd.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 业务实现类：
 */
@Service
@Transactional
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    @Override
    public AjaxResult publish(SearchMasterMsg searchMasterMsg, HttpServletRequest request) {
        //1.对象中的其他属性准备：
        //state状态【0待审核，1审核通过待处理，-1审核失败驳回，2处理完成，3寻主池】
        searchMasterMsg.setState(0);
        // 获取登陆人信息，
        Logininfo logininfo = LoginContext.getLoginfo(request);
        User user = userMapper.findByLogininfoId(logininfo.getId());
        //user_id【哪一个用户发布的=当前登录人】，shop_id【分配给了哪一个店铺】
        searchMasterMsg.setUserId(user.getId());
        //2.添加到数据库
        searchMasterMsgMapper.add(searchMasterMsg);
        //3.百度AI智能审核
        // 标题和名字审核
        Boolean boo1 = BaiduAIUtils.TextCensor(searchMasterMsg.getTitle() + searchMasterMsg.getName());
        // 图片审核
        Boolean boo2 = BaiduAIUtils.ImgsCensor(searchMasterMsg.getResources());
        // 添加日志
        SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
        log.setMsgId(searchMasterMsg.getId()); // 设置消息id
        if (boo1 && boo2) { // 智能审核通过
            //3.1.审核【name，title，resources】通过：state=1，添加审核日志，发短信给用户告诉寻主消息审核通过
            searchMasterMsg.setState(1);
            // 将地址与店铺地址比较，发短信给最近的店铺设置shopId
            Point userPoint = DistanceUtils.getPoint(searchMasterMsg.getAddress());
            Shop nearestShop = DistanceUtils.getNearestShop(userPoint, shopMapper.findAll());
            if (nearestShop == null) { // 没有最近的，设置到寻主池
                searchMasterMsg.setState(3);
            } else {
                searchMasterMsg.setShopId(nearestShop.getId()); // 设置shopId
                // 给店铺管理员发短信通知订单
                Employee employee = employeeMapper.findOne(nearestShop.getAdminId());
                System.out.println("你的店铺有新的订单，请联系用户"
                        + user.getPhone());
            }
            searchMasterMsgMapper.update(searchMasterMsg);
            log.setState(1);
            log.setNote("审核通过");
            searchMasterMsgAuditLogMapper.add(log);
            // 发短信提醒用户审核通过
//            SmsUtils.sendSms(user.getPhone(), "您发布的寻主消息通过审核！");
            System.out.println("您发布的寻主消息通过审核！");
            return new AjaxResult();
        } else {
            //3.2.审核失败驳回：state=-1，添加审核日志，发短信给用户告诉寻主消息审核失败
            searchMasterMsg.setState(-1);
            log.setState(0); // 审核失败
            log.setNote("审核失败");
            searchMasterMsgAuditLogMapper.add(log);
            searchMasterMsgMapper.del(searchMasterMsg.getId());
            // 给用户发送审核失败
            System.out.println("您发布的寻主消息未通过审核！请重新发布！");
            return AjaxResult.me().setSuccess(false).setMessage("您发布的寻主消息未通过审核！请重新发布！");
        }
        //如果获取当前登录人？如何计算离当前用户最近的店铺？如何审核多张图片？
    }

    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery searchMasterMsgQuery, HttpServletRequest request) {
        // 获取当前登陆人信息
        Logininfo loginfo = LoginContext.getLoginfo(request);
        // 设置传递用户id
        User user = userMapper.findByLogininfoId(loginfo.getId());
        searchMasterMsgQuery.setUserId(user.getId());
        // 查询
        return super.queryPage(searchMasterMsgQuery);
    }

    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery searchMasterMsgQuery, HttpServletRequest request) {
        // 设置为已完成状态
        searchMasterMsgQuery.setState(1);
        // 获取当前登陆人信息
        Logininfo loginfo = LoginContext.getLoginfo(request);
        // 判断是否是店铺管理员
        Employee employee = employeeMapper.findByLogininfoId(loginfo.getId());
        if (employee.getShopId() != null) { // 店铺管理员
            searchMasterMsgQuery.setShopId(employee.getShopId());
        }
        return super.queryPage(searchMasterMsgQuery);
    }

    @Override
    public PageList<SearchMasterMsg> toSearchMasterPool(SearchMasterMsgQuery searchMasterMsgQuery) {
        // 设置为寻主池
        searchMasterMsgQuery.setState(3);
        return super.queryPage(searchMasterMsgQuery);
    }

    @Override
    public PageList<SearchMasterMsg> finish(SearchMasterMsgQuery searchMasterMsgQuery, HttpServletRequest request) {
        // 设置为已完成状态
        searchMasterMsgQuery.setState(2);
        // 获取当前登陆人信息
        Logininfo loginfo = LoginContext.getLoginfo(request);
        // 判断是否是店铺管理员
        Employee employee = employeeMapper.findByLogininfoId(loginfo.getId());
        if (employee.getShopId() != null) { // 店铺管理员
            searchMasterMsgQuery.setShopId(employee.getShopId());
        }
        return super.queryPage(searchMasterMsgQuery);
    }

    @Override
    public AjaxResult reject(Long msgId) {
        //一：判断当前寻主消息是否在处理，再处理就抛异常 - 当前订单正在处理
        List<OrderPetAcquisition> orders = orderPetAcquisitionMapper.findeByMsgId(msgId);
        // 遍历判断是否在处理
        if (orders != null && orders.size() > 0) {
            for (OrderPetAcquisition order : orders) {
                if (order.getState() == 0){
                    throw new BusinessException("该订单正在处理，请勿再次操作！");
                }
            }
        }
        searchMasterMsgMapper.reject(msgId);
        return new AjaxResult();
    }

    @Override
    public AjaxResult accept(OrderDto orderDto) {
        //情况1：order == null - 生成订单 //情况2：order！=null&&state=0抛异常
        //情况3：order！=null&&state=1已完成 - 已完成的订单的寻主消息是已经处理完了，不会出现在待处理中
        //情况4：order！=null&&state=-1取消 - a-删除订单，b-生成新的订单，但根据msgID查询的时候可能会有多条数据
        //一：判断当前寻主消息是否在处理，再处理就抛异常 - 当前订单正在处理
        List<OrderPetAcquisition> orders = orderPetAcquisitionMapper.findeByMsgId(orderDto.getMsgId());
        // 遍历判断是否在处理
        if (orders != null && orders.size() > 0) {
            for (OrderPetAcquisition order : orders) {
                if (order.getState() == 0){
                    throw new BusinessException("该订单正在处理，请勿再次接单！");
                }
            }
        }
        //二：生成收购订单
        // 根据id查询寻主消息对象
        SearchMasterMsg msg = searchMasterMsgMapper.findOne(orderDto.getMsgId());
        // 根据该对象生成收购订单
        OrderPetAcquisition order = msgOrderDto2Order(msg,orderDto);
        // 添加
        orderPetAcquisitionMapper.add(order);
        //三：通过处理人去接宠物 - 线下接回宠物
        Employee employee = employeeMapper.findOne(orderDto.getHandler());
        User user = userMapper.findOne(msg.getUserId());
        System.out.println("您有新的订单，请在两天内前往:"+msg.getAddress()+"处理该订单，用户电话为："+user.getPhone());
        return new AjaxResult();
    }

    private OrderPetAcquisition msgOrderDto2Order(SearchMasterMsg msg, OrderDto orderDto) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        // 新增订单表
        order.setOrderSn(CodeGenerateUtils.generateOrderSn(msg.getUserId()));
        order.setDigest(orderDto.getNote());
        order.setLastcomfirmtime(new Date(System.currentTimeMillis() + 2*24*60*60*1000));
        order.setState(0); // 待处理
        order.setPrice(msg.getPrice());
//        order.setPaytype(); // 支付方式
        order.setUserId(msg.getUserId());
        order.setShopId(msg.getShopId());
        order.setAddress(msg.getAddress());
        order.setEmpId(orderDto.getHandler()); // 接单人
        order.setSearchMasterMsgId(msg.getId());
        return order;
    }
}
